/**
 * 
 */
package org.nanhill.osgi.example.web.impl;

import java.util.Map;

import org.nanhill.osgi.example.biz.LoginValidator;
import org.nanhill.osgi.example.manager.AccountNotExist;
import org.nanhill.osgi.example.web.LoginService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;

/**
 * @author lin.wangl
 * 
 */
public class DefaultLoginService implements LoginService {

	private BundleContext bc;

	public DefaultLoginService(BundleContext bc) {
		this.bc = bc;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nanhill.osgi.example.biz.LoginService#valide(java.util.Map)
	 */
	public void valide(Map<String, String> params) throws AccountNotExist {
		String username = params.get("username");
		String pass = params.get("pass");
		String vid = params.get("vid");
		
		System.out.println(username + ":" + pass +":" + vid);
		final String defvid = "default";
		if (vid == null || vid.length() == 0) {
			vid = defvid;
		}

		ServiceReference[] ref = null;
		try { // get input validator
			ref = bc.getServiceReferences(LoginValidator.class.getName(),
					"(id=" + vid + ")");
		} catch (InvalidSyntaxException e1) {
			vid = defvid;
		}

		if (ref == null) { // get default validator
			try {
				ref = bc.getServiceReferences(LoginValidator.class.getName(),
						"(id=" + vid + ")");
			} catch (InvalidSyntaxException e) {
				throw new IllegalStateException(e);
			}
		}

		if (ref == null) {
			throw new IllegalStateException("no vlaid login validator");
		}

		LoginValidator validator = (LoginValidator) bc.getService(ref[0]);

		validator.valide(username, pass);

	}
}
